package cn.exrick.xboot.modules.commonlyUsed.serviceimpl;

import cn.exrick.xboot.modules.commonlyUsed.dao.mapper.UserCommonlyMapper;
import cn.exrick.xboot.modules.commonlyUsed.dto.CommonlyDTO;
import cn.exrick.xboot.modules.commonlyUsed.dto.CommonlyVO;
import cn.exrick.xboot.modules.commonlyUsed.entity.CommonlyUsed;
import cn.exrick.xboot.modules.commonlyUsed.entity.UserCommonly;
import cn.exrick.xboot.modules.commonlyUsed.service.IUserCommonlyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class IUserCommonlyServiceImpl extends ServiceImpl<UserCommonlyMapper, UserCommonly> implements IUserCommonlyService {

    @Autowired
    private UserCommonlyMapper userCommonlyMapper;

    @Override
    public List<CommonlyVO> userCommonlyList(CommonlyDTO commonlyDTO) {

        List<CommonlyVO> userCommonlyList = userCommonlyMapper.userCommonlyList(commonlyDTO.getOrgId(),commonlyDTO.getUserId());
        return userCommonlyList;
    }

    @Override
    public boolean InsertCommonly(CommonlyDTO commonlyDTO) {
        List<CommonlyUsed> userCommonlyList = commonlyDTO.getCommonlyUseds();

        LambdaQueryWrapper<UserCommonly> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(UserCommonly::getOrgId, commonlyDTO.getOrgId());
        deleteWrapper.eq(UserCommonly::getUserId, commonlyDTO.getUserId());

        if (null != userCommonlyList && !userCommonlyList.isEmpty()) {
            userCommonlyMapper.delete(deleteWrapper);
            for (CommonlyUsed commonlyUsed : userCommonlyList) {
                LambdaQueryWrapper<UserCommonly> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserCommonly::getOrgId, commonlyDTO.getOrgId());
                queryWrapper.eq(UserCommonly::getUserId, commonlyDTO.getUserId());
                queryWrapper.eq(UserCommonly::getFunctionCode, commonlyUsed.getId());
                UserCommonly isExist = userCommonlyMapper.selectOne(queryWrapper);

                if (null == isExist) {
                    UserCommonly userCommonly = new UserCommonly();
                    userCommonly.setId(UUID.randomUUID().toString());
                    userCommonly.setUserId(commonlyDTO.getUserId());
                    userCommonly.setOrgId(commonlyDTO.getOrgId());
                    userCommonly.setFunctionCode(commonlyUsed.getId());
                    userCommonlyMapper.insert(userCommonly);
                }
            }
            return true;
        }else {
            userCommonlyMapper.delete(deleteWrapper);
            return true;
        }
    }


}

